#------------------------ Station Script ---------------------------
#This script is fired by a cron Job to syschronize with the server.
# --- run command : python station.py option
#Actions to perform :
#1/ Open the socket with the server
#2/ Compress and send the history table
#3/ Get the new users string list and update the user table

#Created by Mathieu Martel - 02-08-2010 
#-------------------------------------------------------------------

import sqlite3
import sys
import socket
#import os.path

#Creates test tables
#Note: We have to figure out where to create these tables, another script to update each od these tables?

#Global init
connection_user = sqlite3.connect('user.db')
connection_history = sqlite3.connect('history.db')
cursor_users = connection_user.cursor()
cursor_history = connection_history.cursor()


def init_tables():
	cursor_history.execute('CREATE TABLE IF NOT EXISTS history (user_id INTEGER PRIMARY KEY, bike_id INTEGER, time VARCHAR(10))')
	cursor_users.execute('CREATE TABLE IF NOT EXISTS users (user_id INTEGER PRIMARY KEY)')
	
	#Create data
	cursor_users.execute('INSERT INTO users VALUES (null)')
	cursor_users.execute('INSERT INTO users VALUES (null)')
	cursor_users.execute('INSERT INTO users VALUES (null)')

	#Formation for the time : Hour:min:AM/PM
	cursor_history.execute('INSERT INTO history VALUES (null, 1, "3:15:A")')
	cursor_history.execute('INSERT INTO history VALUES (null, 2, "3:35:A" )')
	return


def read_tables():

	#Retrieve data

	cursor_users.execute('SELECT * FROM users')
	for row in cursor_users:
		print '_'*10
		print 'ID:', row[0]
	
	cursor_history.execute('SELECT * FROM history')
	for row in cursor_history:
		print '_'*10
		print 'User_id:', row[0]	
		print 'Bike_id:', row[1]
		print 'Time:', row[2]
	return


def clean_tables():
	cursor_history.execute('DELETE FROM history')
	cursor_users.execute('DELETE FROM users')
	return



def sync():
	
	#Open socket
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)		#Create a socket object
	host = 'localhost' #socket.getaddrinfo('localhost', None)		#Get local machine name
	port = 12345			#Port for the service
	
	s.connect((host, port))	
	
	#compress and send history
	print s.recv(1024)

	#clear history table
	#get new users
	#update users

	s.close()
	return



#Get the script arg and run procedure
#Note : could create a dictionnary to switch between procedures

arg = sys.argv[1]
print arg

if arg == 'test':
	init_tables()
	read_tables()
	clean_tables() 

if arg == 'sync':
	sync()
